pipeline {
    agent {
        //指定此Pipeline将在动态Jenkins Slave中执行
        label '192-168-103-249'
    }
    options {
        //设置管道运行的超时时间，在此之后，Jenkins将中止管道
        timeout(time: 20, unit: 'MINUTES')
        // 失败重试次数
        retry(2)
        //输出时间戳
        timestamps()
    }
    environment {
        //构建分支 master、test
        // Brand='test'
        //定义Maven编译环境 dev、test、prod
        PROFILES_ACTIVE = "stable"
        //jar包名称
        JAR_NAME = 'yss-datamiddle-quality.jar'
        //日志名称
		LOG_NAME = 'yss-datamiddle-quality'
		//日志目录
		LOG_NAME_PATH="/data2/dataMiddle/logs/${LOG_NAME}"
		//jar包备份的目录 
		JAR_BAK_PATH="/data2/dataMiddle/data_bak/jar_bak"
		
		//会把JAR_PATH目录下的jar包复制到此目录下后，再启动jar包
        JAR_RUN_PATH="/data2/dataMiddle/dataMiddle_jar"
        //JOB所在根目录
        WORKSPACE_PATH = "/opt/dataMiddle-service/workspace/${JOB_NAME}/"
        //配置文件路径
        conf_yaml="${WORKSPACE_PATH}/src/main/resources/application.yml"
    }
    stages {
        stage('创建目录'){
			steps{
			    // 创建jar包备份目录
				dir("${JAR_BAK_PATH}") {
			      sh ''''''
                } 
				// 创建日志目录
				dir("${LOG_NAME_PATH}") {
			      sh ''' '''
                }
                // 创建日志目录
				dir("${JAR_RUN_PATH}") {
			      sh ''' '''
                }
				
		    }
        }
		stage('备份jar包'){
				steps{
					dir("${WORKSPACE_PATH}") {
					  sh '''
						 if [ -f "${JAR_RUN_PATH}/${JAR_NAME}" ];then
							cp -r ${JAR_RUN_PATH}/${JAR_NAME}  ${JAR_BAK_PATH}/${LOG_NAME}/$(date +%Y%m%d.%H:%M:%S)-${JAR_NAME}
							echo "jar包备份成功..."
						 else
							echo "备份的jar包不存在！"
						 fi
					  '''
					} 
				}
			}
		stage('删除jar包,保存10个jar包'){
				steps{
					dir("${JAR_BAK_PATH}/${LOG_NAME}") {
					 sh '''
						count=`ls -lR| grep "^-" | wc -l`
						if [ ${count} -le 10 ];
						then
							echo "jar包小于等于10"
						else
						   del_coun=`expr ${count} - 9`
						   del=`ls -lthr|head -${del_coun}| grep -E '*${JAR_NAME}*'| grep ^[^d] | awk '{print $9}'`
						   
						   for i in ${del}
						   do
							 rm -rf $i
						   done;
						   echo "jar包大于10,删除成功"
						fi
					 '''
					} 
					
				}
		}
		stage('获取代码'){
			steps{
				echo "拉取代码"
				cleanWs()
			    checkout([$class: 'GitSCM', branches: [[name: '$branch_tag']], extensions: [], userRemoteConfigs: [[credentialsId: 'b6756a14-1393-410e-82c1-62a07d5ae936', url: 'http://192.168.101.94:8081/Data-Middleground-Develop-Area/product-code/datamiddle-backend/datamiddle-business/datamiddle-dataquality.git']]])
			}
		}
		stage('修改配置文件信息') {
		    //修改服务间调用ip
		    //修改redis地址ip
			//数据库服务地址ip及实例
            steps {
                echo "修改配置文件信息！！！！！！！！！！！"
                sh '''
                  sed -i 's/192\\.168\\.100\\.132/192\\.168\\.103\\.249/g' ${conf_yaml}	
                  sed -i 's/192\\.168\\.100\\.128/192\\.168\\.103\\.249/g' ${conf_yaml}	
                  sed -i 's/192\\.168\\.100\\.130/192\\.168\\.103\\.249/g' ${conf_yaml}	
                  sed -i 's/192\\.168\\.100\\.149/192\\.168\\.103\\.249/g' ${conf_yaml}
                  '''
            }
        }
        stage('Build project package') {
            steps {
                dir("${WORKSPACE_PATH}") {
				  echo "开始执行打包操作......."
                  //利用maven对项目进行build
                  sh "mvn -Dmaven.test.skip=true clean package"
               }
            }
        }
        stage('Run Application') {
            steps {
                dir("${WORKSPACE_PATH}") {
                  // 如果程序已经启动，杀掉进程
				  sh '''
				    count=`ps -ef | grep ${JAR_NAME} | grep -v "grep" | wc -l`
                    if [ $count -gt 0 ]; then
                        ps aux|grep ${JAR_NAME}|grep -v grep|awk '{print $2}'|xargs kill -9
                    fi
                    '''
                  echo "将jar包复制至启动目录下"
                  sh '''cp -rf target/${JAR_NAME}  ${JAR_RUN_PATH}/${JAR_NAME}'''
                  echo "启动程序......."
                  //利用maven对项目进行build
                  sh '''
                  JENKINS_NODE_COOKIE=dontKillMe
                  nohup /usr/local/jdk/jdk-11.0.10/bin/java -jar  ${JAR_RUN_PATH}/${JAR_NAME} --spring.profiles.active=${PROFILES_ACTIVE}  --datamiddle.data.export=false --testlog.path=${LOG_NAME_PATH} & 
                  '''
              }
            }
        }
    }
    post {
        success {
             echo "'${env.JOB_NAME} [${env.BUILD_NUMBER}]' 构建成功"
        }
        failure {
            echo "'${env.JOB_NAME} [${env.BUILD_NUMBER}]' 构建失败"
        }
    }
}